$(function() {
	//当前用户基本属性
	var phone = sessionStorage.getItem("phone");
	var userId = sessionStorage.getItem("userId");
    var userImg = "static/img/fire-1.jpg";
	console.log("phone:" + phone);
	console.log("userId:" + userId);

    var friendImg = "mui/images/shuijiao.jpg";

	//webSocket
    //建立socket连接
    var socket;
    if(!typeof(WebSocket)) {
        alert("您的浏览器不支持WebSocket");
    }
	if(socketPath == null || socketPath == undefined){
		socketPath = apiPath.replace("https", "ws").replace("http", "ws");
	}
	var createNum = 0;
	function createSocket(){
        var socketUrl= socketPath + "/im/" + userId;
        console.log(socketUrl);
		//ws://127.0.0.1:7070/im/1
        if(_isNull(phone) || _isNull(userId)){
            debugger;
        }

        // 实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
        socket = new WebSocket(socketUrl);

		//打开事件
		socket.onopen = function() {
			console.log("websocket已打开");
			//createSocket();
			//socket.send("这是来自客户端的消息" + location.href + new Date());
		};
		//获得消息事件
		socket.onmessage = function(msg) {
			var objson = JSON.parse(msg.data);
			var code = objson.code;
            //console.log("code：" + code);
			if(code == 200){ //心跳
                return;
            }
            console.log("获取消息：" + msg.data);
            if(code == 0){
                var friendId = $("#friendId").val();
                if(friendId == objson.friendId){
                    var limsg1 = start1 + objson.content + "<span></span></p></div></a></li>";
                    $("#msg_ul").append(limsg1);
                    uptHeight();
                }
            }
			if(code == 100 || code == 300){
				console.log("刷新好友")
				//createUserList();
			}
		};
		//关闭事件
		socket.onclose = function() {
			console.log("websocket已关闭：" + createNum);
            createNum++;
			if(createNum < 3){
                createSocket();
            }
		};
		//发生了错误事件
		socket.onerror = function() {
			console.log("websocket发生了错误:" + createNum);
            createNum++;
            if(createNum < 3){
                createSocket();
            }
		};
	}
    //发送消息
    $("#submit").click(function(){
        var content = $("#content").val();
        console.log(content);
        if(content == undefined || content == ""){
            layer.msg('不能发送空白消息', {icon: 5});
        }else{
            var friendId = $("#friendId").val();
            console.log("friendId:" + friendId);

            var param = {};
            param["event"] = "chatMsg";
            param["friendId"] = friendId;
            param["content"] = content;
            param["sequenceId"] = new Date().getTime();
            var params = JSON.stringify(param);
            console.log("发送：" + params);
            socket.send(params);

            var limsg = start2 + content;
            limsg = limsg + "<span></span></p></div></a></li>";
            $("#msg_ul").append(limsg);
            $("#content").val("");
            uptHeight();
        }
    });
    setInterval(function() {
    	if(WebSocket.OPEN === socket.readyState){
            var param = {};
            param["event"] = "heartbeat";
            param["userId"] = userId;
            param["sequenceId"] = new Date().getTime();
            var params = JSON.stringify(param);
            //console.log("发送心跳：" + params);
            socket.send(params);
		}else{
            console.log("socket closed " + socket.readyState);
		}
    }, 10 * 1000);
    setInterval(function() {
        if(createNum >= 3){
            createNum = 0;
        }
    }, 2 * 60 * 1000);

	if(_isNull(phone) || _isNull(userId)){
		login();
	}else{
		findUsers();
	}
    $("#msg_ul").hide();
    $(".msg-text").hide();

    $("#chatTab").text("首页");
    $(".nav_ul").html("<li class='li_this' data-id='home'>首页</li>");
	function findUsers(){
		$.ajax({
			type: "get",
			url: apiPath + "/user/findUsers",
			data: {
				'phone': phone
			},
			success: function(data) {
				console.log(data);
				if(data.code == 0) {
					$.each(data.data,function(index,value){
						console.log(value);
						let str = "<li data-id='"+value.userId+"'>"+ value.name +"</li>";
						$(".nav_ul").append(str);
					});
				} else {
					layer.msg(data.msg, {icon: 5});
				}

				$(".left_div li").on("click", function(){
					console.log($(this).text());
					let navId = $(this).attr("data-id");
					let navName = $(this).text();
					console.log("昵称:" + navName);

					$(".left_div li").each(function(){
						let id = $(this).attr("data-id");
						if(navId == id){
							$(this).addClass("li_this");
						}else{
							$(this).removeClass("li_this");	
						}
					})
                    if('home' == navId){
                        $(".home_div").show();
                        $("#msg_ul").hide();
                        $(".msg-text").hide();

                        $("#chatTab").text("首页");
                        $("#friendId").val("");
                    }else{
                        $(".home_div").hide();
                        $("#msg_ul").show();
                        $(".msg-text").show();

                        $("#chatTab").text(navName);
                        $("#friendId").val(navId);
                        getMsgList(navId);
                    }
				})
                //好友切换、即左侧菜单栏中内容 ，触发点击事件
                $('.site-demo-active').on('click', function() {
                    var dataid = $(this).attr("data-id");
                    console.log("好友ID:" + dataid);
                    var datatitle = $(this).attr("data-title");
                    console.log("昵称:" + datatitle);
                    if('home' == dataid){
                        $(".home_div").show();
                        $("#msg_ul").hide();
                        $(".msg-text").hide();

                        $("#chatTab").text("首页");
                        $("#friendId").val("");
                    }else{
                        $(".home_div").hide();
                        $("#msg_ul").show();
                        $(".msg-text").show();

                        $("#chatTab").text(datatitle);
                        $("#friendId").val(dataid);
                        getMsgList(dataid);
                    }
                });
			}
		});
		createSocket();
	}

    //消息模板-好友消息
    var start1 = "<li class='mui-table-view-cell mui-media'><a href='javascript:;'>";
    start1 = start1 + "<img class='mui-media-object mui-pull-left' src='"+friendImg+"' style='margin-right:0px'>";
    start1 = start1 + "<div class='f_msg_div'><p class='msg1'>";
    //我的消息
    var start2 = "<li class='mui-table-view-cell mui-media'><a href='javascript:;'>";
    start2 = start2 + "<img class='mui-media-object mui-pull-right' src='"+userImg+"'>";
    start2 = start2 + "<div class='my_msg_div'><p class='msg2'>";
	function getMsgList(friendId) {
	    console.log("获取消息记录");
        //消息列表
        $.ajax({
            type: "get",
            url: apiPath + "/chat/getMsg",
            data: {
                'friendId': friendId,
                'userId': userId
            },
            success: function(data) {
                console.log(data);
                if(data.code == 0) {
                    $("#msg_ul").html("");
                    for(var i = 0;i < data.data.length;i++){
                        let item = data.data[i];
                        var listr;
                        if(item.userId == userId){
                            listr = start2 + item.content;
                        }
                        if(item.friendId == userId){
                            listr = start1 + item.content;
                        }
                        listr = listr + "<span></span></p></div></a></li>";
                        $("#msg_ul").append(listr);
                    }
                    uptHeight();
                }
            }
        });
    }
	//回车监听
    $(document).keyup(function (event) {
        if (event.keyCode == 13) {
            $("#submit").click();
        }
    });

    function login() {
        layer.open({
            type: 2, //类型：1-html,2-解析url
            closeBtn: 0, //关闭按钮是否显示 1显示0不显示
            title: '登录', //页面标题
            shadeClose: false, //点击遮罩区域是否关闭页面
            shade: 0.5,
            //遮罩透明度
            area: ['600px', '340px'],
            //弹出层页面比例
            content: 'login.html', //弹出层的url
            end: function() {
                //关闭事件,无论是确认还是取消，只要层被销毁了，end都会执行，不携带任何参数。
                console.log("关闭事件");
                //location.reload();　　 //layer.open关闭刷新
                phone = sessionStorage.getItem("phone");
                userId = sessionStorage.getItem("userId");
                if(_isNull(phone)){
                    layer.alert("手机号记录失败");
                }else{
                    findUsers();
                }
            }
        });
    }

	$("#reLogin").click(function () {
		login();
    });

    var facityHeight = 0; //固定不变
    if(window.innerHeight) {
        facityHeight = window.innerHeight;
    } else if((document.body) && (document.body.clientHeight)) {
        facityHeight = document.body.clientHeight;
    }
    var html = document.getElementsByTagName('html')[0];
    if(document.body.offsetHeight < facityHeight) {
        html.style.height = facityHeight;
    }
    console.log("高度=" + facityHeight);

    function uptHeight(){
        //setTimeout(function(){
            var thisHeight = $(this).height(); //获取当前页面高度(不包含输入法)
            //$('#msg2').text("thisHeight="+ thisHeight);
            var maxHei = facityHeight * 0.3;
            if (facityHeight - thisHeight > maxHei) {
                //$('#msg3').text("A弹出");
                $(document).scrollTop($(document).height()-(facityHeight - thisHeight));
            } else {
                //$('#msg3').text("A收起");
                $(document).scrollTop($(document).height()-facityHeight);
            }
        //},400)
    }
})